let spreadNS = GC.Spread.Sheets;
let config = GC.Spread.Sheets.Designer.DefaultConfig;

window.onload = function () {
    const spread = createSpreadAndDesigner();
    injectAI(spread);
    initSpread(spread);
};
// 创建Spread 和 Designer
function createSpreadAndDesigner() {
    const demoHost = document.getElementById("demo-host");
    const designer = new GC.Spread.Sheets.Designer.Designer(demoHost, undefined, undefined, { sheetCount: 4 });

    return designer.getWorkbook();
}

// 初始化Spread
function initSpread(spread) {
    // 打开动态数组
    spread.options.allowDynamicArray = true;

    // 加载示例文件
    fetch("sample.sjs")
        .then((res) => res.blob())
        .then((blob) => {
            spread.open(blob);
        });
}

// 向 Spread 注入AI服务
function injectAI(spread) {

    // 准备服务端回调
    const serverCallback = async (requestBody) => {
        const response = await fetch(getAIApiUrl(), {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(requestBody),
        });
        if (response.status === 429) {
            alert("The server is busy, please try again later.");
            return;
        }
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response;
    };
        
    spread.injectAI(serverCallback);
}

function getAIApiUrl() {
    return "./api/queryAI";
}

function _getElementById(id) {
    return document.getElementById(id);
}